
package com.us.install;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.monlyu.util.PropertyUtil;

public class Install extends HttpServlet {

    private static String ROOT_PATH = "";

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        ROOT_PATH = req.getSession().getServletContext().getRealPath("/");
        String path = ROOT_PATH + "WEB-INF/classes/dbconfig.properties";
        PropertyUtil.store(NetServlet.content, path);
        System.out.println("Store proptifile");
        try {
            if ("true".equals(NetServlet.content.get("db.createnew"))) {
                System.out.println("Create Database");
                createDB();
            }
            File webbk = new File(ROOT_PATH + "setup/config/web_bp.xml");
            if (!webbk.exists()) {
                FileUtils.copyFile(new File(ROOT_PATH + "WEB-INF/web.xml"), new File(ROOT_PATH
                    + "setup/config/web_bp.xml"));
            }
            //insertSQL();
            FileUtils.copyFileToDirectory(
                new File(ROOT_PATH + "setup/config/web.xml"),
                new File(ROOT_PATH + "WEB-INF/"));
            resp.getWriter().write("成功创建。请关闭窗口，重新启动startup.bat");
            System.exit(0);
        }
        catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("创建失败:原因>" + e.getMessage());
        }
    }

    private void createDB() throws Exception{
        Map<String, String> kv = NetServlet.content;
        Class.forName("com.mysql.jdbc.Driver");
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = DriverManager.getConnection(kv.get("db.createurl"), kv.get("db.user"), kv.get("db.passwd"));
        Statement stat = conn.createStatement();
        String sql = "drop database if exists " + kv.get("db.name");
        stat.execute(sql);
        sql = "create database " + kv.get("db.name") + " charset utf8;";
        stat.execute(sql);
        stat.close();
        conn.close();
    }

    private void insertSQL() throws Exception{
        System.out.println("正在复制数据，请等待");
        Map<String, String> kv = NetServlet.content;
        Class.forName("com.mysql.jdbc.Driver");
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        String url = String.format(
            "jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=utf8",
            kv.get("db.host"),
            kv.get("db.port"),
            kv.get("db.name"));
        Connection conn = DriverManager.getConnection(url, kv.get("db.user"), kv.get("db.passwd"));
        Statement stat = conn.createStatement();
        // String sql = FileUtils.readFileToString(new File(ROOT_PATH +
        // "WEB-INF/classes/baseData/initData.sql"));
        List<String> sqls = readSql(ROOT_PATH + "WEB-INF/classes/baseData/initData.sql");
        for (String string : sqls) {
            stat.execute(string);
        }
        stat.close();
        conn.close();
        System.out.println("正在复制数据完成，请等待");
    }

    public static List<String> readSql(String fileName) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
        List<String> sqlList = new ArrayList<String>();
        StringBuilder sqlSb = new StringBuilder();
        String s = null;
        while ((s = br.readLine()) != null) {
            if (s.startsWith("/*") || s.startsWith("#") || StringUtils.isBlank(s)) {
                continue;
            }
            if (s.endsWith(";")) {
                sqlSb.append(s);
                sqlSb.setLength(sqlSb.length() - 1);
                sqlList.add(sqlSb.toString());
                sqlSb.setLength(0);
            } else {
                sqlSb.append(s);
            }
        }
        br.close();
        return sqlList;
    }
}
